Java 集合框架源码分析(二)——LinkedList

介绍

LinkedList 也是Java集合框架的重要组成部分。其中类层次结构如下。

java.lang.Object 
继承者 java.util.AbstractCollection 
继承者 java.util.AbstractList 
继承者 java.util.AbstractSequentialList 
继承者 java.util.LinkedList

LinkedList 直接继承于AbstractSequentialList。JDK中对AbstractSequentialList的说明如下:

This class provides a skeletal implementation of the List 
interface to minimize the effort required to implement this interface 
backed by a “sequential access” data store (such as a linked list). For 
random access data (such as an array), AbstractList should be used in preference to this class.

AbstractSequentialList为顺序访问的数据存储结构提供了一个骨架类实现,如果要支持随机访问,则优先选择AbstractList类继承。LinkedList 基于链表实现,因此它继承了AbstractSequentialList

源码分析

以下源码基于sun JDK 1.7,为了便于理解,对部分源码加了中文注释。

package java.util;

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    // LinkedList中元素个数 
    transient int size = 0;

   //第一个节点(非头节点)
    transient Node<E> first;

   //末尾节点
    transient Node<E> last;

    /**
     * 默认构造函数:创建一个空的链表 
     */
    public LinkedList() {
    }

    /**
     * 包含“集合”的构造函数:创建一个包含“集合”的LinkedList 
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    /**
     * Links e as first element.
     */
    private void linkFirst(E e) {
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }

    /**
     * Links e as last element.
     */
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

    /**
     * Inserts element e before non-null Node succ.
     */
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

    /**
     * Unlinks non-null first node f.
     */
    private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        final E element = f.item;
        final Node<E> next = f.next;
        f.item = null;
        f.next = null; // help GC
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }

    /**
     * Unlinks non-null last node l.
     */
    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        final E element = l.item;
        final Node<E> prev = l.prev;
        l.item = null;
        l.prev = null; // help GC
        last = prev;
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }

    /**
     * Unlinks non-null node x.
     */
    E unlink(Node<E> x) {
        // assert x != null;
        final E element = x.item;
        final Node<E> next = x.next;
        final Node<E> prev = x.prev;

        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }

        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }

    //返回链表中第一个元素
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    //返回链表中最后一个元素
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

    /**
     * 删除LinkedList的第一个元素 
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    /**
     * 删除LinkedList的最后一个元素
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    /**
     * 将元素添加到LinkedList的起始位置
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * 将元素添加到LinkedList的结束位置   
     */
    public void addLast(E e) {
        linkLast(e);
    }

    /**
     * 判断LinkedList是否包含元素(o)
     */
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

    /**
     * 返回LinkedList的大小 
     */
    public int size() {
        return size;
    }

    /**
     * 将元素(E)添加到LinkedList中 
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    /**
     * 从LinkedList中删除元素(o)  
     * 从链表开始查找,如存在元素(o)则删除该元素并返回true;
     * 否则,返回false。 
     */
    public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 将“集合(c)”添加到LinkedList中。 
     * 实际上,是从双向链表的末尾开始,将“集合(c)”添加到双向链表中。 
     */
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

    /**
     * 从双向链表的index开始,将“集合(c)”添加到双向链表中。
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node<E> pred, succ;
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            succ = node(index);
            pred = succ.prev;
        }

        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }

        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }

    /**
     * 清空双向链表
     */
    public void clear() {
        // Clearing all of the links between nodes is "unnecessary", but:
        // - helps a generational GC if the discarded nodes inhabit
        //   more than one generation
        // - is sure to free memory even if there is a reachable Iterator
        for (Node<E> x = first; x != null; ) {
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }

    /**
     * 返回LinkedList指定位置的元素 
     */
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

    /**
     * 设置index位置对应的节点的值为element 
     */
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

    /**
     * 在index前添加节点,且节点的值为element  
     */
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

    /**
     *  删除index位置的节点
     */
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

    //判断索引是否合法
    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

    /**
     * Tells if the argument is the index of a valid position for an
     * iterator or an add operation.
     */
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

    //越界异常信息封装
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }
   //检查是否越界
    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    //检查是否位置越界
    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 返回指定index位置处的Node.
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

    /**
    * 从前向后查找,返回“值为对象(o)的节点对应的索引”    
    * 不存在就返回-1    
     */
    public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }

    /**
     * // 从后向前查找,返回“值为对象(o)的节点对应的索引”    
     * // 不存在就返回-1 
     */
    public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }

    // Queue operations.

    /**
     * 返回第一个节点 
     * 若LinkedList的大小为0,则返回null 
     */
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    /**
     * 返回第一个节点  
     * 若LinkedList的大小为0,则抛出异常
     */
    public E element() {
        return getFirst();
    }

    /**
     * 删除并返回第一个节点 若LinkedList的大小为0,则返回null 
     *
     */
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

     // 删除并返回第一个节点    
    // 若LinkedList的大小为0,则返回null  
    public E remove() {
        return removeFirst();
    }

    // 将e添加双向链表末尾  
    public boolean offer(E e) {
        return add(e);
    }

      // 将e添加双向链表开头  
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

     // 将e添加双向链表末尾  
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

     // 返回第一个节点    
    // 若LinkedList的大小为0,则返回null  
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
     }

    // 返回最后一个节点    
    // 若LinkedList的大小为0,则返回null 
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

   // 删除并返回第一个节点    
    // 若LinkedList的大小为0,则返回null 
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    // 删除并返回最后一个节点    
    // 若LinkedList的大小为0,则返回null 
    public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }

    // 将e插入到双向链表开头 
    public void push(E e) {
        addFirst(e);
    }

    // 删除并返回第一个节点 
    public E pop() {
        return removeFirst();
    }

     // 从LinkedList开始向后查找,删除第一个值为元素(o)的节点    
    // 从链表开始查找,如存在节点的值为元素(o)的节点,则删除该节点
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    // 从LinkedList末尾向前查找,删除第一个值为元素(o)的节点    
    // 从链表开始查找,如存在节点的值为元素(o)的节点,则删除该节点 
    public boolean removeLastOccurrence(Object o) {
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     *  返回“index到末尾的全部节点”对应的ListIterator对象(List迭代器)
     */
    public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }
      // List迭代器    
    private class ListItr implements ListIterator<E> {
        // 上一次返回的节点  
        private Node<E> lastReturned = null;
         // 下一个节点   
        private Node<E> next;
        // 下一个节点对应的索引值    
        private int nextIndex; 
         // 期望的改变计数。用来实现fail-fast机制。    
        private int expectedModCount = modCount;
         // 构造函数。    
        // 从index位置开始进行迭代  
        ListItr(int index) {
            // assert isPositionIndex(index);
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }
        // 是否存在下一个元素
        public boolean hasNext() {
            return nextIndex < size;
        }
        // 获取下一个元素 
        public E next() {
            checkForComodification();
            if (!hasNext())
                throw new NoSuchElementException();

            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.item;
        }
         // 是否存在上一个元素  
        public boolean hasPrevious() {
            return nextIndex > 0;
        }
        // 获取上一个元素   
        public E previous() {
            checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();

            lastReturned = next = (next == null) ? last : next.prev;
            nextIndex--;
            return lastReturned.item;
        }
        // 获取下一个元素的索引   
        public int nextIndex() {
            return nextIndex;
        }
        // 获取上一个元素的索引   
        public int previousIndex() {
            return nextIndex - 1;
        }
        // 删除当前元素。    
        // 删除双向链表中的当前节点 
        public void remove() {
            checkForComodification();
            if (lastReturned == null)
                throw new IllegalStateException();

            Node<E> lastNext = lastReturned.next;
            unlink(lastReturned);
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            expectedModCount++;
        }
      // 设置当前节点为e   
        public void set(E e) {
            if (lastReturned == null)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.item = e;
        }
        // 将e添加到当前节点的前面    
        public void add(E e) {
            checkForComodification();
            lastReturned = null;
            if (next == null)
                linkLast(e);
            else
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }
       //判断 “modCount和expectedModCount是否相等”,依次来实现fail-fast机制。
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    /**
    * 双向链表的节点所对应的数据结构。    
        * 包含3部分:上一节点,下一节点,当前节点值。 
    */
    private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

    /**
     * 反向迭代器 
     * @since 1.6
     */
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

    /**
     * 反向迭代器实现类。 
     */
    private class DescendingIterator implements Iterator<E> {
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }

    @SuppressWarnings("unchecked")
    private LinkedList<E> superClone() {
        try {
            return (LinkedList<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    }

    /**
     * 克隆函数。返回LinkedList的克隆对象。
     */
    public Object clone() {
        LinkedList<E> clone = superClone();

        // Put clone into "virgin" state
        clone.first = clone.last = null;
        clone.size = 0;
        clone.modCount = 0;

        // Initialize clone with our elements
        for (Node<E> x = first; x != null; x = x.next)
            clone.add(x.item);

        return clone;
    }

    /**
     *  返回LinkedList的Object[]数组
     */
    public Object[] toArray() {
        Object[] result = new Object[size];
        int i = 0;
        for (Node<E> x = first; x != null; x = x.next)
            result[i++] = x.item;
        return result;
    }

    /**
     * 返回LinkedList的模板数组。所谓模板数组,即可以将T设为任意的数据类型 
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            a = (T[])java.lang.reflect.Array.newInstance(
                                a.getClass().getComponentType(), size);
        int i = 0;
        Object[] result = a;
        for (Node<E> x = first; x != null; x = x.next)
            result[i++] = x.item;

        if (a.length > size)
            a[size] = null;

        return a;
    }

    private static final long serialVersionUID = 876323262645176354L;

    /**
     * Sjava.io.Serializable的写入函数 
     * 将LinkedList的“容量,所有的元素值”都写入到输出流中 
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        //  写入“容量”  
        s.writeInt(size);

        // 将链表中所有节点的数据都写入到输出流中 
        for (Node<E> x = first; x != null; x = x.next)
            s.writeObject(x.item);
    }

    /**
     * java.io.Serializable的读取函数:根据写入方式反向读出  
     * 先将LinkedList的“容量”读出,然后将“所有的元素值”读出
     */
    @SuppressWarnings("unchecked")
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();

        // 从输入流中读取“容量”
        int size = s.readInt();

        // 从输入流中将“所有的元素值”并逐个添加到链表中
        for (int i = 0; i < size; i++)
            linkLast((E)s.readObject());
    }
}

ast-fail 失败机制

Java 容器的一种保护机制,能够防止多个进程同时修改同一个容器的内容。如果在你迭代遍历某个容器的过程中,另一个进程介入其中,并且插入,删除或修改此容器内的某个对象,那么就会出现问题:也许迭代过程已经处理过容器中的该元素了,也许还没处理,也许在调用size()之后容器的尺寸收缩了——还有许多灾难场景。Java容器类类库采用fast-fail机制,它会探查容器上的任何除了你的进程所进行的操作以外的所有变化,一旦它发现其他进程修改了容器,就会立刻抛出ConcurrentModificationException 异常,而不是等到事后来检查问题。

分析

LinkedList 结构大致如下图所示,这是一个基于双向链表的结构。 
这里写图片描述

  1. LinkedList 基于双向链表实现,不存在容量不足的问题,没有扩容方法。
  2. LinkedList中允许元素为null
  3. LinkedList 没有同步机制,因此LinkedList也是非同步的。
  4. LinkedList 基于链表实现,插入和删除效率较高,时间复杂度O(1),查找效率较低,虽然有一个加速操作。
  5. 注意源码中的 Node<E> node(int index)方法。该方法返回双向链表中指定位置处的节点,而链表中是没有下标索引的,要指定位置出的元素,就要遍历该链表,从源码的实现中,我们看到这里有一个加速动作。源码中先将index与长度size的一半比较,如果indexsize/2,就只从位置size往前遍历到位置index处。这样可以减少一部分不必要的遍历,从而提高一定的效率(实际上效率还是很低)。
  6. 源码中还实现了栈和队列的操作方法,因此LinkedList 也可以用作栈,队列和双端队列来使用。

对比ArrayList

那么在上篇《Java 集合框架源码分析(一)——ArrayList》中基于数组实现的ArrayList 到底有啥区别,两者的使用场景又是什么?带着这个疑问继续分析。

List只是一个接口,而LinkedList、ArrayList是List接口的不同实现。有很多相似之处。

相同点:均是非同步的实现。 
不同点:内部实现机制不同,LinkedList 基于链表,ArrayList基于数组,导致常用操作的性能不同。

首先对比下常用操作的算法复杂度

LinkedList

get(int index) : O(n) 
add(E element) : O(1) 
add(int index, E element) : O(n) 
remove(int index) : O(n) 
Iterator.remove() : O(1) <— LinkedList的主要优点 
ListIterator.add(E element) is O(1) <— LinkedList的主要优点

ArrayList

get(int index) : O(1) <— ArrayList的主要优点 
add(E element) : 基本是O(1) , 因为动态扩容的关系,最差时是 O(n) 
add(int index, E element) : 基本是O( n - index) , 因为动态扩容的关系,最差时是 O(n) 
remove(int index) : O(n - index) (例如,移除最后一个元素,是 O(1)) 
Iterator.remove() : O(n - index) 
ListIterator.add(E element) : O(n - index)

LinkedList,因为本质是个链表,所以通过Iterator来插入和移除操作的耗时,都是个恒量,但如果要获取某个位置的元素,则要做指针遍历。因此,get操作的耗时会跟List长度有关。

对于ArrayList来说,得益于快速随机访问的特性,获取任意位置元素的耗时,是常量的。但是,如果是add或者remove操作,要分两种情况,如果是在尾部做add,也就是执行add方法(没有index参数),此时不需要移动其他元素,耗时是O(1),但如果不是在尾部做add,也就是执行add(int index, E element),这时候在插入新元素的同时,也要移动该位置后面的所有元素,以为新元素腾出位置,此时耗时是O(n-index)。另外,当List长度超过初始化容量时,会自动生成一个新的array(长度是之前的1.5倍),此时会将旧的array移动到新的array上,这种情况下的耗时是O(n)。

总之,get操作,ArrayList快一些。而add操作,两者差不多。(除非是你希望在List中间插入节点,且维护了一个Iterator指向指定位置,这时候linkedList能快一些,但是,我们更多时候是直接在尾部插入节点,这种特例的情况并不多)在大部分情况下,使用ArrayList会好一些。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值